import {createStore} from 'redux'

import Vote from '../types/vote'

//定义state的接口约束
interface StateInterface{
    votelist:Vote[]
}

//给state一个初始值
let initState:StateInterface = {
    votelist:[]
}

let reducer = (state=initState,action:any) => {
    switch (action.type) {
        //初始化数据
        case 'INIT_DATA':
            return {votelist:[...action.votelist]};
        //投票
        case 'ADD_VOTE':{
            //vid  num  id:选项的id
            let index = state.votelist.findIndex(item => item.id === action.vid);
            let target = state.votelist[index]; //查找到指定投票
            for(let i = 0;i<target.items.length;i++){
                if(target.items[i].id === action.id){
                    //修改数量
                    target.items[i].num = action.num+1;
                    //添加投票人
                    let username = localStorage.getItem('username') || '';
                    target.voteUsers.push(username)
                }
            }
            state.votelist[index] = {...target};
            return {votelist:[...state.votelist]}
        }
        default:
            return state;
    }
}

let store = createStore(reducer);

export default store